import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './Test.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
@connect(({ fund, loading }) => ({
  fund,
  loading: loading.models.ruleTest,
}))
@Form.create()
class HighPremiums extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      method: 'GetList',
      page: 1,
      pagesize: 100,
      field: '',
      adesc: '',
      type: 3,
      name: '',
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},

    dataTradeList: {},
    updateParam: true,

    premiumrate: '100%',
    pricerate: '100%',
  };

  columns = [
    /*      {
            title: '序号',
            dataIndex: 'p',
            fixed: 'left',
          }, */
    {
      title: '股票代码',
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '类型',
      dataIndex: 'typename',
      filters: [
        {
          text: 'Sell Put',
          value: 'Sell Put',
        },
        {
          text: 'Sell Call',
          value: 'Sell Call',
        },
      ],
      onFilter: (value, record) => {
        if (record.typename != undefined) {
          return record.typename.indexOf(value) === 0;
        }
      },
      render: tags => {
        return <span>{tags == 'Sell Call' ? 'SC' : tags == 'Sell Put' ? 'SP' : ''}</span>;
      },
    },
    /*    {
      title: '',
      dataIndex: 'id',
      render: text => <span >{}</span>,
    }, */
    {
      title: '执行价',
      dataIndex: 'strikeprice',
    },
    {
      title: '当前价',
      dataIndex: 'closeprice',
      render: text => {
        return <span>{Math.floor(text * 100) / 100}</span>;
      },
    },

    {
      title: '距执行幅度',
      dataIndex: 'pricerate',
      render: text => {
        let priceratetext = '';
        if (text > 0) {
          priceratetext = `${text}%`;
        }
        return <span>{priceratetext}</span>;
      },
      sorter: true,
    },
    {
      title: '成本价',
      dataIndex: 'costprice',
    },

    {
      title: '现价',
      dataIndex: 'newprice',
    },
    {
      title: '剩余期权比',
      dataIndex: 'premiumrate',
      render: text => {
        let premiumratetext = '';
        if (text > 0) {
          premiumratetext = `${text}%`;
        }
        return <span>{premiumratetext}</span>;
      },
      sorter: true,
    },

    {
      title: '股数',
      dataIndex: 'stocknumber',
    },
    {
      title: '当日盈亏',
      dataIndex: 'thisincome',
      sorter: true,
      render: (tags, record) => {
        const bili = record.thisincome / (record.stocknumber * record.costprice);
        let color = '';
        if (bili < -0.4) {
          color = '#be5eed';
        } else if (bili > -0.4 && bili < -0.2) {
          color = '#9218cd';
        } else if (bili > -0.2 && bili < 0) {
          color = '#601386';
        } else if (bili == 0) {
          color = '#201a23';
        } else if (bili > 0 && bili < 0.2) {
          color = '#f86d75';
        } else if (bili > 0.2 && bili < 0.4) {
          color = '#f3353f';
        } else if (bili > 0.2) {
          color = '#c70f19';
        } else {
          color = '#8a0a11';
        }
        return <span style={{ color }}>{tags}</span>;
      },
    },
    {
      title: '盈亏金额',
      dataIndex: 'allincome',
      sorter: (a, b) => a.allincome - b.allincome,
    },
    {
      title: '初始期权金',
      dataIndex: 'allpremium',
      sorter: (a, b) => a.allpremium - b.allpremium,
    },
    {
      title: '剩余期权金',
      dataIndex: 'remainpremium',
      sorter: (a, b) => a.remainpremium - b.remainpremium,
    },

    {
      title: '操作时间',
      dataIndex: 'tradedate',
      sorter: true,
    },
    {
      title: '到期时间',
      dataIndex: 'expiry',
      sorter: true,
    },
    {
      title: '剩余天数',
      dataIndex: 'remaindays',
    },
    {
      title: '头寸规模',
      dataIndex: 'sumprice',
      sorter: (a, b) => a.sumprice - b.sumprice,
      fixed: 'right',
    },
  ];

  // 默认加载数据-起始方法
  render() {
    const {
      fund: { data },
      loading,
      total,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: data.rows,
      pagination: {
        current: this.state.formValues.page,
        pageSize: this.state.formValues.pagesize,
        total: parseInt(data.total),
      },
    };
    /* if(typeof(data.rows)!="undefined"){
      newdata.list.splice(this.state.formValues.pagesize,1)
    }; */

    return (
      <PageHeaderWrapper title="高权利金期权持仓列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.paginationMsg}>
              {'共'} {newdata.pagination.total} {'条数据'}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={listLoading}
              data={newdata}
              columns={this.columns}
              pagination={false}
              onChange={this.handleStandardTableChange}
              rowKey="id"
              scroll={{ x: 'auto' }}
              bordered
              rowClassName={(record, index) => {
                let textcolor = '';
                if (
                  parseFloat(record.premiumrate) >= parseFloat(this.state.premiumrate) ||
                  parseFloat(record.pricerate) >= parseFloat(this.state.pricerate)
                ) {
                  textcolor = styles.lineback;
                }
                return textcolor;
              }}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, dataTradeList } = this.state;
    dispatch({
      type: 'fund/GetHighPremiumsList',
      payload: formValues,
      callback: response => {
        if (response.total > 0) {
          let stockNumber = 0;
          let thisIncome = 0.0;
          let allIncome = 0.0;
          let allPremium = 0.0;
          let remainPremium = 0.0;
          let sumPrice = 0.0;
          for (let i = 0; i < response.total; i++) {
            stockNumber += response.rows[i].stocknumber;
            thisIncome = parseFloat(response.rows[i].thisincome) + thisIncome;
            allIncome = parseFloat(response.rows[i].allincome) + allIncome;
            remainPremium = parseFloat(response.rows[i].remainpremium) + remainPremium;
            sumPrice = parseFloat(response.rows[i].sumprice) + sumPrice;
            allPremium = parseFloat(response.rows[i].allpremium) + allPremium;
          }
          response.rows.splice(0, 0, {
            name: '期权合计',
            stocknumber: stockNumber,
            thisincome: thisIncome.toFixed(2),
            allincome: allIncome.toFixed(2),
            allpremium: allPremium.toFixed(2),
            remainpremium: remainPremium.toFixed(2),
            sumprice: sumPrice.toFixed(2),
            closeprice: '',
            id: 10000002,
          });
        }
        this.setState({
          dataTradeList: response.rows,
        });
      },
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    if (sorter.field) {
      formValues.field = `${sorter.field}`;

      if (sorter.order == 'ascend') {
        formValues.adesc = 'asc'; // 升序
      } else if (sorter.order == 'descend') {
        formValues.adesc = 'desc'; // 降序
      } else {
        formValues.adesc = ''; // 不排序
      }
    } else {
      formValues.field = '';
      formValues.adesc = '';
    }
    formValues.page = pagination.current;
    formValues.pagesize = pagination.pageSize;
    const params = {
      ...formValues,
    };
    dispatch({
      type: 'fund/GetHighPremiumsList',
      payload: params,
      callback: response => {
        if (response.total > 0) {
          let stockNumber = 0;
          let thisIncome = 0.0;
          let allIncome = 0.0;
          let allPremium = 0.0;
          let remainPremium = 0.0;
          let sumPrice = 0.0;
          for (let i = 0; i < response.total; i++) {
            stockNumber += response.rows[i].stocknumber;
            thisIncome = parseFloat(response.rows[i].thisincome) + thisIncome;
            allIncome = parseFloat(response.rows[i].allincome) + allIncome;
            remainPremium = parseFloat(response.rows[i].remainpremium) + remainPremium;
            sumPrice = parseFloat(response.rows[i].sumprice) + sumPrice;
            allPremium = parseFloat(response.rows[i].allpremium) + allPremium;
          }
          response.rows.splice(0, 0, {
            name: '期权合计',
            stocknumber: stockNumber,
            thisincome: thisIncome.toFixed(2),
            allincome: allIncome.toFixed(2),
            allpremium: allPremium.toFixed(2),
            remainpremium: remainPremium.toFixed(2),
            sumprice: sumPrice.toFixed(2),
            closeprice: '',
            id: 10000002,
          });
        }
        this.setState({
          dataTradeList: response.rows,
        });
      },
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={5} sm={20}>
            <FormItem label="股票代码">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={5} sm={20}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>

          <Col md={5} sm={20}>
            <FormItem label="剩余期权比">
              {getFieldDecorator('premiumrate', {
                initialValue: this.state.premiumrate,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={5} sm={20}>
            <FormItem label="距执行价幅度">
              {getFieldDecorator('pricerate', {
                initialValue: this.state.pricerate,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={3} sm={12}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={this.UpdateRecordColor}>
                修改
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  UpdateRecordColor = e => {
    const {
      dispatch,
      form,
      fund: { data },
    } = this.props;
    const { premiumrate, pricerate } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        premiumrate: values.premiumrate,
        pricerate: values.pricerate,
      });
    });
  };

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      fund: { data },
    } = this.props;
    const { formValues, dataTradeList } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      data.rows = dataTradeList.filter(
        (item, index, arr) => item.name.indexOf(values.name.toUpperCase() || '') == 0
      );
      this.setState({
        updateParam: !this.state.updateParam,
      });
    });
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.maxEarningsDate = '';
    formValues.minBreakEvenMargin = 0;
    formValues.minEarningsDate = '';
    formValues.minRoyalty = 0;
    formValues.minYieldRate = 0;

    dispatch({
      type: 'fund/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };
}

export default HighPremiums;
